<?php
/**
 * 企业资质申请控制器
 */

namespace app\admin\controller;

use app\common\model\Apply;
use app\common\model\Cate;
use app\common\model\Company;
use app\common\model\User;
use app\common\validate\ApplyValidate;
use Exception;
use think\db\Query;
use think\Request;
use think\response\Json;

class ApplyController extends AdminBaseController {

	/**
	 * 列表
	 * @param Request $request
	 * @param Apply $model
	 * @return string
	 * @throws Exception
	 */
	public function index(Request $request, Apply $model): string {
		$param = $request->param();
		$data = $model->with(['cate'])->scope('where', $param)
			->paginate([
				'list_rows' => $this->admin['admin_list_rows'],
				'var_page' => 'page',
				'query' => $request->get(),
			]);
		// 关键词，排序等赋值
		$this->assign($request->get());

		$this->assign([
			'data' => $data,
			'page' => $data->render(),
			'total' => $data->total(),
			'cate_list' => Cate::select(),
			'status_list' => Apply::STATUS_LIST,
		]);
		return $this->fetch();
	}

	/**
	 * 添加
	 * @param Request $request
	 * @param Apply $model
	 * @param ApplyValidate $validate
	 * @return string|Json
	 * @throws Exception
	 */
	public function add(Request $request, Apply $model, ApplyValidate $validate) {
		if ($request->isPost()) {
			$param = $request->param();
			$validate_result = $validate->scene('admin_add')->check($param);
			if (!$validate_result) {
				return admin_error($validate->getError());
			}

			$result = $model::create($param);

			$url = URL_BACK;
			if (isset($param['_create']) && (int) $param['_create'] === 1) {
				$url = URL_RELOAD;
			}
			return $result ? admin_success('添加成功', [], $url) : admin_error();
		}
		$this->assign([
			'cate_list' => Cate::select(),
			'status_list' => Apply::STATUS_LIST,
		]);

		return $this->fetch();
	}

	/**
	 * 修改
	 * @param $id
	 * @param Request $request
	 * @param Apply $model
	 * @param ApplyValidate $validate
	 * @return string|Json
	 * @throws Exception
	 */
	public function edit($id, Request $request, Apply $model, ApplyValidate $validate) {
		$data = $model->findOrEmpty($id);
		if ($request->isPost()) {
			$param = $request->param();
			$check = $validate->scene('admin_edit')->check($param);
			if (!$check) {
				return admin_error($validate->getError());
			}

			$result = $data->save($param);
			if ($param['status'] == 1) {
				$this->enable($id, $model);
			} elseif ($param['status'] == 2) {
				$this->disable($id, $model);
			}
			return $result ? admin_success('修改成功', [], URL_BACK) : admin_error('修改失败');
		}

		$this->assign([
			'data' => $data,
			'cate_list' => Cate::select(),
			'status_list' => Apply::STATUS_LIST,
		]);

		return $this->fetch('add');
	}
	public function dishone($id, Request $request, Apply $model) {
		$data = $model->findOrEmpty($id);

		$this->assign([
			'data' => $data,
		]);
		return $this->fetch();
	}
	/**
	 * 删除
	 * @param mixed $id
	 * @param Apply $model
	 * @return Json
	 */
	public function del($id, Apply $model): Json {
		$check = $model->inNoDeletionIds($id);
		if (false !== $check) {
			return admin_error('ID为' . $check . '的数据不能被删除');
		}

		$result = $model::destroy(static function ($query) use ($id) {
			/** @var Query $query */
			$query->whereIn('id', $id);
		});

		return $result ? admin_success('删除成功', [], URL_RELOAD) : admin_error('删除失败');
	}

	public function enable($id, Apply $model): Json {

		$result = $model->whereIn('id', $id)->update(['status' => 1]);
		$list = $model->whereIn('id', $id)->select()->toArray();
		foreach ($list as $key => $value) {
			$company = Company::where('company_name', $value['company_name'])->findOrEmpty();
			if ($company->isEmpty()) {
				$company_data = $value;
				$company_data['cate'] = $value['cate'];
				unset($company_data['id'], $company_data['create_time'], $company_data['update_time'], $company_data['delete_time']);
				$res = Company::create($company_data);

				$user_data = [
					'user_level_id' => 1,
					'company_id' => $res->id,
					'username' => $value['phone'],
					'password' => '123456',
					'mobile' => $value['phone'],
					'nickname' => $value['company_name'],
				];
				User::create($user_data);
			} else {

				$company_data = [];
				$company_data['cate'] = $company_data['cate'] . ',' . $value['cate'];
				if (empty($company['other'])) {
					$company_data['other'] = $value['other'];
				} else {
					$company_data['other'] = $company['other'] . ',' . $value['other'];
				}
				$company_data['equity'] = $value['equity'];
				$company_data['car_num1'] = $value['car_num1'];
				$company_data['car_num2'] = $value['car_num2'];
				$company_data['equity_cert'] = $value['equity_cert'];
				$company_data['iso9001'] = $value['iso9001'];
				// $company_data['iso14001'] = $value['iso14001'];
				// $company_data['haccp'] = $value['haccp'];
				//$company_data['cnas'] = $value['cnas'];
				$res = $company->save($company_data);

			}
			//$this->send_sms('2044647', [], [$value['phone']]);
		}

		return $result ? admin_success('审核成功', [], URL_RELOAD) : admin_error();
	}

	public function disable($id, Apply $model): Json {
		$result = $model->whereIn('id', $id)->update(['status' => 2]);
		$list = $model->whereIn('id', $id)->select()->toArray();
		foreach ($list as $key => $value) {
			$this->send_sms('2051617', [], [$value['phone']]);
		}

		return $result ? admin_success('拒绝成功', [], URL_RELOAD) : admin_error();
	}

	public function export(Request $request, Apply $model) {
		$param = $request->param();
		$data = $model->scope('where', $param)->select();

		$header = ['ID', '公司名称', '统一社会信用代码', '所属类目', '公司性质', '纳税人资质', '联系人姓名', '手机号', '邮箱', '经营场地地址', '面积', '产权'];
		$body = [];
		foreach ($data as $item) {
			$record = [];
			$record['id'] = $item->id . ' ';
			$record['company_name'] = $item->company_name . ' ';
			$record['code'] = $item->code . ' ';
			$record['cate'] = implode(',', Cate::whereIn('id', $item->cate)->column('name')) . ' ';
			$record['nature'] = $item->nature . ' ';
			$record['aptitude'] = $item->aptitude . ' ';
			$record['name'] = $item->name . ' ';
			$record['phone'] = $item->phone . ' ';
			$record['email'] = $item->email . ' ';
			$record['address'] = $item->address . ' ';
			$record['area'] = $item->area . ' ';
			$record['equity'] = $item->equity . ' ';

			$body[] = $record;
		}
		$this->exportData($header, $body, '企业资质申请数据-' . date('YmdHis'));
	}
}
